package nuc.edu.cn.config;

import nuc.edu.cn.handle.MyAccessDenyHandle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter{
    @Autowired
    MyAccessDenyHandle myAccessDenyHandle;
    @Autowired
    UserDetailsService userDetailsService;
    @Autowired
    DataSource dataSource;
//    @Autowired
//    PersistentTokenRepository persistentTokenRepository;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                //当发现时/login时认为时登录，必须和表单提交的地址一致，取执行UserDetailsServiceImpl
                .loginProcessingUrl("/login")
                //自定义登录界面
                .loginPage("/login.html")
                //登录成功后的页面，post请求
                .successForwardUrl("/toMain")
                //和successForwardUrl不能一起用
//                .successHandler(new MyAuthenticationSuccessHandle("http://www.baidu.com"))
                .failureForwardUrl("/toError");
//                .failureHandler(new MyAuthenticationFailureHandle("error.html"));


        http.authorizeRequests()
                .antMatchers("/error.html").permitAll()
               //login.html不需要被认证
                .antMatchers("/login.html").permitAll()
                //image目录下的所有文件都被放行
//                .antMatchers("/images/**").permitAll()
                //后缀为png的放行
//                .regexMatchers(".+[.]png").permitAll()
                //当有全局配置mvc.servlet
//                .mvcMatchers("/Demo").servletPath("/wjj").permitAll()
//                .antMatchers("/main1.html").hasAuthority("admin")
//                .antMatchers("/main1.html").hasRole("abc")
//                .antMatchers("/main1.html").hasIpAddress("127.0.0.1")
                //所有请求都要认证，必须登录后访问
                .anyRequest().authenticated();
        http.csrf().disable();
        //异常处理
        http.exceptionHandling()
                .accessDeniedHandler(myAccessDenyHandle);
        http.rememberMe()
                //失效时间
                .tokenValiditySeconds(60)
                //自定义登录逻辑
                .userDetailsService(userDetailsService)
                //持久层对象
                .tokenRepository(repository());
        http.logout()
                //指定推出的地址名字
//                .logoutUrl()
                .logoutSuccessUrl("/login.html");


    }
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    @Bean
    public PersistentTokenRepository repository(){
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(dataSource);
        //第一次启动时会自动建表，第二次注释掉否则报错
//        jdbcTokenRepository.setCreateTableOnStartup(true);
        return jdbcTokenRepository;
    }

}
